/*
Copyright 2015 chanven

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package com.aiju.cash.ui.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.app.DataProviderManager;
import com.aiju.app.config.ConfigManager;
import com.aiju.base.activity.BaseActivity;
import com.aiju.base.fragment.BaseFragment;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.LoginApi;
import com.aiju.cash.core.event.AppEvent;
import com.aiju.cash.receiver.MyReceiver;
import com.aiju.cash.ui.login.LoginActivity;
import com.aiju.cash.ui.login.manager.LoginManager;
import com.aiju.cash.ui.main.fragment.BlotterFragment;
import com.aiju.cash.ui.main.fragment.HomeFragment;
import com.aiju.cash.ui.multiple_shops.activity.ClerkActivity;
import com.aiju.cash.ui.pay.manager.PrintManager;
import com.aiju.cash.ui.setting.AboutActivity;
import com.aiju.cash.ui.setting.PaySettingActivity;
import com.aiju.cash.ui.setting.RateActivity;
import com.aiju.cash.ui.setting.StoreActivity;
import com.aiju.cash.ui.setting.UserActivity;
import com.aiju.cash.util.CheckVersion;
import com.aiju.cash.util.PollingService;
import com.aiju.cash.widgit.SlidingMenu;
import com.aiju.common.ActivityStack;
import com.aiju.common.ImageLoader;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.utils.AppUtil;
import com.aiju.utils.L;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.SimpleDialog;
import com.aiju.widgit.layout.AiJuTabBarView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.aiju.cash.R.id.tv_menu_out;

/**
 * @author: 佐为
 * @date: 2016-11-10 14:42
 * @version: V1.0
 * @Description: 主页
 */
public class MainActivity extends BaseActivity implements AiJuTabBarView.OnTabReselectedListener,
        View.OnClickListener {

    /**
     * 底部导航
     */
    private AiJuTabBarView mAiJuTabBarView;

    private FragmentManager mFragmentManager;
    private BaseFragment currentFragment;
    private List<BaseFragment> fragments;

    private SlidingMenu mSlidingMenu;

    private ImageView headerImageView;
    private TextView shopNameTextView, userRaleTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AppUtil.mainActivity = this;
        if (DataProviderManager.getDataProvider().getModel().equals("V1")) {
            PrintManager.getInstance().bindPrintService(this);
        }

        //设置底部菜单导航
        mAiJuTabBarView = (AiJuTabBarView) findViewById(R.id.downbar);
        mAiJuTabBarView.setOnTabReselectedListener(this);
        mAiJuTabBarView.setViewHolderCreator(new AiJuTabBarView.ViewHolderCreator() {
            @Override
            public AiJuTabBarView.ViewHolderBase createViewHolder() {
                return new DemoViewHolder();
            }
        });

        mFragmentManager = getSupportFragmentManager();

        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new BlotterFragment());
       /* fragments.add(new SettingFragment());*/
        currentFragment = fragments.get(0);
        mFragmentManager.beginTransaction().add(R.id.fl_container, fragments.get(0)).commit();
        new CheckVersion(this).updateApp();

        initSlidingMenu();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MyReceiver.MESSAGE_RECEIVED_ACTION);
        registerReceiver(myReceiver, filter);

        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(AppEvent event) {
                //T.ToastShort("主页接收");
                new SimpleDialog(AppUtil.currentActivity)
                        .setTitileText("检测到您的账号发生变动，请重新登录")
                        .setLeftText("确定")
                        .setRightText("")
                        .setOnSimpleClick(new SimpleDialog.OnSimpleClick() {
                            @Override
                            public void onCancel() {
                                new LoginManager(MainActivity.this, mDialogHelper).loginOut(mUser);
                            }

                            @Override
                            public void onSubmit() {
                            }
                        }).setLayoutParams().setCanceledOnTouchOutside(false).setCancelable(false).show();

            }
        }).tryToRegisterIfNot();
        startService(new Intent(this, PollingService.class));
    }

    //初始化左侧菜单
    private void initSlidingMenu() {
        mSlidingMenu = (SlidingMenu) findViewById(R.id.id_menu);
        mSlidingMenu.setOnScrollChang(new SlidingMenu.OnScrollChang() {
            @Override
            public void move() {
                tintManager.setStatusBarAlpha(0);
            }

            @Override
            public void back() {
                tintManager.setStatusBarAlpha(255);
            }
        });

        if (mUser.isAdmin()) {
            findViewById(R.id.iv_menu_right).setVisibility(View.VISIBLE);
            findViewById(R.id.rl_user_info).setOnClickListener(this);
        }
        findViewById(R.id.tv_user_setting).setOnClickListener(this);
        if (mUser.isAdmin()) {
            findViewById(R.id.tv_clerk_setting).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_clerk_setting).setOnClickListener(this);
        }
        findViewById(R.id.tv_menu_about).setOnClickListener(this);
        findViewById(R.id.tv_menu_rale).setOnClickListener(this);
        findViewById(R.id.tv_menu_setting).setOnClickListener(this);
        findViewById(tv_menu_out).setOnClickListener(this);

        headerImageView = (ImageView) findViewById(R.id.iv_user_header);
        shopNameTextView = (TextView) findViewById(R.id.tv_shop_name);
        userRaleTextView = (TextView) findViewById(R.id.tv_user_role);

        ImageLoader.loadImage(headerImageView, mUser.getShopImageUrl());
        shopNameTextView.setText(mUser.getShopName());
        userRaleTextView.setText("您是" + mUser.getRoleString());
    }

 /*    @Override
    protected void onResume() {
       ImageLoader.loadImage(headerImageView, mUser.getShop().getImageUrl());
        shopNameTextView.setText(mUser.getShop().getShopName());
        userRaleTextView.setText(mUser.getRoleString());
        super.onResume();
    }*/

    public boolean closeMenu() {
        if (mSlidingMenu.isOpen()) {
            mSlidingMenu.closeMenu();
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() != tv_menu_out) {
            if (mSlidingMenu.isOpen()) {
                mSlidingMenu.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSlidingMenu.closeMenu();
                    }
                }, 500);
            }
        }
        switch (v.getId()) {
            case R.id.rl_user_info:
                startActivity(StoreActivity.class);
                break;
            case R.id.tv_user_setting:
                startActivity(UserActivity.class);
                break;
            case R.id.tv_clerk_setting:
                Intent intent = new Intent(this, ClerkActivity.class);
                intent.putExtra("shop", mUser.getShop());
                startActivity(intent);
                break;
            case R.id.tv_menu_about:
                startActivity(AboutActivity.class);
                break;
            case R.id.tv_menu_rale:
                startActivity(RateActivity.class);
                break;
            case R.id.tv_menu_setting:
                startActivity(PaySettingActivity.class);
                break;
            case tv_menu_out:
                new LoginApi().logout(mUser.getToken(), ConfigManager.getInstance().getRegId(), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        T.ToastNetError();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isSuccess()) {
                            T.ToastShort("注销成功");
                            PreferencesUtils.putString(MainActivity.this, "password", "");
                            ActivityStack.finishAll();
                            startActivity(LoginActivity.class);
                        } else {
                            T.ToastShort("注销失败");
                            L.e(dataJson.getMsg());
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(myReceiver);
        // BaiduTTSManager.getInstance().destroy();
        stopService(new Intent(this, PollingService.class));
        super.onDestroy();
    }

    /**
     * 后台推送
     */
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String extras = intent.getStringExtra("extras");
           /* String massage = intent.getStringExtra("message");*/
            DataJson dataJson = null;
            try {
                JSONObject jsonObject = new JSONObject(extras);
                dataJson = new DataJson(jsonObject.getString("json"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (dataJson.isSuccess()) {
                String data = dataJson.getData().toString();
                String msg = dataJson.getMsg();

                if (data.equals("unbind")) {//删除店员
                    new SimpleDialog(AppUtil.currentActivity)
                            .setTitileText("检测到您的账号发生变动，请重新登录")
                            .setLeftText("确定")
                            .setRightText("")
                            .setOnSimpleClick(new SimpleDialog.OnSimpleClick() {
                                @Override
                                public void onCancel() {
                                    new LoginManager(MainActivity.this, mDialogHelper).loginOut(mUser);
                                }

                                @Override
                                public void onSubmit() {
                                }
                            }).setLayoutParams().setCanceledOnTouchOutside(false).setCancelable(false).show();

                }

                if (data.equals("kick")) {//多账号登录
                    new SimpleDialog(AppUtil.currentActivity)
                            .setTitileText("检测你的账号在另一台设备上登录，此设备已退出，请确保是本人操作。")
                            .setLeftText("切换账号")
                            .setRightText("重新登录")
                            .setOnSimpleClick(new SimpleDialog.OnSimpleClick() {
                                @Override
                                public void onCancel() {
                                    new LoginManager(MainActivity.this, mDialogHelper).loginOut(mUser);
                                }

                                @Override
                                public void onSubmit() {
                                    String name = PreferencesUtils.getString(MainActivity.this, "name");
                                    String password = PreferencesUtils.getString(MainActivity.this, "password");
                                    new LoginManager(MainActivity.this, mDialogHelper).login(name, password);
                                }
                            }).setLayoutParams().setCanceledOnTouchOutside(false).setCancelable(false).show();
                }

                //语音
                // speak(data,msg);
            }
        }

    };

    @Override
    public void onTabReselected(int position) {
        switchFragment(fragments.get(position));
        if (position == 1) {
            mSlidingMenu.setTouchMode(false);
        } else {
            mSlidingMenu.setTouchMode(true);
        }
    }

    private void switchFragment(BaseFragment targetFragment) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (!targetFragment.isAdded()) {
            transaction
                    .hide(currentFragment)
                    .add(R.id.fl_container, targetFragment)
                    .commit();
        } else {
            transaction
                    .hide(currentFragment)
                    .show(targetFragment)
                    .commit();
        }
        currentFragment = targetFragment;
    }

    /**
     * 底部导航适配
     */
    private static class DemoViewHolder extends AiJuTabBarView.ViewHolderBase {
        private View rootView;
        private String[] tabText = {"收银", "流水"};
        private int[] tabIcon = {
                R.drawable.tab_home_selector,
                R.drawable.tab_report_selector};

        @Override
        public View createView(LayoutInflater layoutInflater, int position) {
            rootView = layoutInflater.inflate(R.layout.layout_tab, null);
            ImageView mImageView = (ImageView) rootView.findViewById(R.id.tab_image);
            TextView mTextView = (TextView) rootView.findViewById(R.id.tab_text);
            mImageView.setImageResource(tabIcon[position]);
            mTextView.setText(tabText[position]);
            return rootView;
        }

        @Override
        public void updateView(int position, boolean isCurrent) {
            if (isCurrent) {
                rootView.setSelected(true);
            } else {
                rootView.setSelected(false);
            }
        }
    }

    public SlidingMenu getSlidingMenu() {
        return mSlidingMenu;
    }

}
